# 代码行数比对接口
import gitlab
import requests
try:
    from urllib import quote_plus  # Python 2.X
    from urlparse import urljoin
except ImportError:
    from urllib.parse import quote_plus, urljoin
import os
from urllib.parse import quote 
import urllib
import ctypes, sys
import subprocess
import json; 
import xlrd,xlwt
from xlutils.copy import copy
import sys
# ------------获取版本信息-------------


# 输入gitlab地址
url = 'http://10.252.171.20:21080/'
# （需要替换）输入自己账户认证的登陆token
token = 'glpat-wk-CoYx14jKyf4rtm6Zs'
# 输入代比对的代码信息表
codeExcelName='git版本比对.xls'
# 获取代码信息表中的模块名称
moduleName=[]
# 获取代码信息表中的分支名称
branchName=[]
# 获取代码信息表中的新版本代码模块reversion号
newReversion=[]
# 获取代码信息表中的旧版本代码模块reversion号
oldReversion=[]
# 获取代码信息表中的待查询代码模块reversion号
targetRversion=[]
# 代码比对方法codeCompare()
def codeCompare(projectName,oldVersion,newVersion):
    sumLineAdd = 0
    sumLineDelete = 0
    sumFileAdd = 0
    sumFileDelete = 0
    sumFileRename = 0
    sumFileModefied = 0
    sumResult=[]
    # 获取excel文档
    workbook= xlrd.open_workbook(codeExcelName)
    # 获取excel文档指定表[0]
    sheet1 = workbook.sheet_by_name(projectName)# 获取excel文档指定表[0]
    row1 =  sheet1.row_values(0)
    #第一行
    for j in range(0,len(row1)):
        if oldVersion == row1[j]:
            print(oldVersion,j)
            oldIndex=j
        elif newVersion == row1[j]:
            print(newVersion,j)
            newIndex=j
        else:
            continue
        print(j)
    # print(type(row1[0]))

    # 获取列数据
    moduleName = sheet1.col_values(0)#第0列：项目名
    branchName = sheet1.col_values(1)#第1列：分支名
    newReversion = sheet1.col_values(newIndex)#第2列：起始reversion
    oldReversion = sheet1.col_values(oldIndex)#第3列：结束reversion
    for i in range(1,len(moduleName)): 
        #登录 自建
        gl = gitlab.Gitlab(url, token)
        try:
            projects = gl.projects.list(search=moduleName[i])
            project = gl.projects.get(projects[0].id,ref=branchName[i])
            result = project.repository_compare(oldReversion[i],newReversion[i])
            # print(gl.projects.list())
            print(moduleName[i])
            # print(result)
            # 行数增加
            lineadd = 0 
            # 行数删除
            linedelete = 0 
            # 文件增加
            fileadd = 0 
            # 文件删除
            filedelete = 0 
            # 文件重命名
            filerename = 0 
            # 文件修改
            fileModefied = 0 
            for file_diff in result['diffs']:
                # print(file_diff)
                fileModefied += 1
                # 行数增加=file_diff的增加值
                lineadd += str(file_diff).count('\\n+')
                # 行数减少=file_diff的减少值
                linedelete += str(file_diff).count('\\n-')
                # 如果file_diff的'new_file'值为true
                if file_diff['new_file']:
                    # 文件新增+1
                    fileadd +=1
                # 如果file_diff的'deleted_file'值为true
                elif file_diff['deleted_file']:
                    # 文件删除+1
                    filedelete +=1
                # 如果file_diff的'renamed_file'值为true
                elif file_diff['renamed_file']:
                    # 重命名文件+1
                    filerename +=1
            # print("lineadd:",lineadd)
            # print("linedelete:",linedelete)
            # print("fileadd:",fileadd)
            # print("filedelete:",filedelete)
            # print("filerename:",filerename)
            # print("fileModefied:",fileModefied)
            sumFileAdd = sumFileAdd+fileadd
            sumFileDelete = sumFileDelete+filedelete
            sumLineAdd  = sumLineAdd+lineadd
            sumLineDelete = sumLineDelete+linedelete
            sumFileRename = sumFileRename+filerename
            sumFileModefied = sumFileModefied+fileModefied
        except Exception as ex:
            print("moduleName:",moduleName[i]," 异常啦:",ex)
            continue
    # print([('总增加行数：',sumLineAdd),('总删除行数：',sumLineDelete),('总增加文件数：',sumFileAdd),('总删除文件数：',sumFileDelete),('总修改名称文件数：',filerename),('总修改文件数：',fileModefied)])
    # print([sumLineAdd,sumLineDelete,sumFileAdd,sumFileDelete,sumFileRename,sumFileModefied])
    sumResult = [sumLineAdd,sumLineDelete,sumFileAdd,sumFileDelete,sumFileRename,sumFileModefied]
    return sumResult
# 代码行数查询方法codeLineCount()
def codeLineCount(projectName,targetVersion):  
        sumtotal_lines=0    # 代码修改总行数      
        sumadditions=0      # 代码新增总行数
        sumdeletions=0      # 代码删除总行数
        checkResult=[]
        workbook= xlrd.open_workbook(codeExcelName) # 获取excel文档
        # sheet1 = workbook.sheet_by_index(0)
        sheet1 = workbook.sheet_by_name(projectName)# 获取excel文档指定表[0]
        row1 =  sheet1.row_values(0)
        #便利查询指定的版本信息
        for j in range(0,len(row1)):
            if targetVersion == row1[j]:
                print(targetVersion,j)
                targetIndex=j
            else:
                continue
        # 获取列数据
        moduleName = sheet1.col_values(0)#第0列：项目名
        branchName = sheet1.col_values(1)#第1列：分支名
        targetReversion = sheet1.col_values(targetIndex)#第2列：起始reversion
        # 创建 GitLab 对象
        gl = gitlab.Gitlab(url, token)
        for i in range(0,len(moduleName)):
            try:
                # print(moduleName[i])
                # 获取项目
                projects = gl.projects.list(search=moduleName[i])
                project = gl.projects.get(projects[0].id,ref_name=branchName)
                # 获取指定版本的代码总行数
                commit1 = project.commits.get(targetReversion[i], project_id=project.id, ref_name=branchName)
                # print(commit)
                total_lines = commit1.stats["total"]
                additions = commit1.stats["additions"]
                deletions = commit1.stats["deletions"]
                sumtotal_lines=sumtotal_lines+total_lines
                sumadditions=sumadditions+additions
                sumdeletions=sumdeletions+deletions
                # print('ppi的总增加行数为：',additions1)
            except Exception as ex:
                print("异常啦:",ex)
        print('新版本代码修改行数统计结果：')
        print('总修改行数：',sumtotal_lines)
        print('总增加行数：',sumadditions)
        print('总删除行数：',sumdeletions)
        checkResult.append(sumtotal_lines)
        checkResult.append(sumadditions)
        checkResult.append(sumdeletions)
        return checkResult
# 主程序调用
if __name__ == "__main__":
    # 获取项目名称
    projectName='智慧安检项目'
    # 获取待查询的版本号
    targetVersion='3.1.3.130'
    # 获取待查询的版本信息下标
    targetIndex=''
    # 获取项目旧版本
    oldVersion='3.1.3.126'
    # 获取项目旧版本信息栏下标
    oldIndex=''
    # 获取项目新版本
    newVersion='3.1.3.130'
    # 获取项目新版本信息栏下标
    newIndex=''
    # 调用代码比对方法codeCompare
    codeCompareResult = codeCompare(projectName,oldVersion,newVersion)
    codeLineCountResult = codeLineCount(projectName,targetVersion)
    print(codeLineCountResult)
    print(codeCompareResult)
    